from rest_framework.views import APIView
from rest_framework.response import Response
from apps.minapp.models import Admins
from utils import sendmail
from email.mime.text import MIMEText
from utils.jwt_auth import create_token
from utils.randomcode import randomsting


class RegisterView(APIView):
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        print(request.data['form'])
        send_type = request.data['send_type']
        mail = dict()
        if send_type == "register":  # 如果是注册
            code = str(randomsting(9))  # 密码
            message = "Hi," + request.data['form']['username'] + ".\n你的邮箱注册初始密码是" + code
        else:  # 如果是其他操作即更改密码
            code = str(randomsting(16))  # 验证码
            message = "Hi," + request.data['form']['username'] + ".\n你的密码修改验证码是" + code
        # mail.update({
        #     "host": "smtp.yeah.net",
        #     "port": "465",
        #     "user": "eatfun_backend@yeah.net",
        #     "pwd": "SNMZYLPFMPJGXMPO",
        #     "sender": "eatfun_backend@yeah.net",
        #     "subject": "[EatFun]账号注册验证码",  # 主题
        #     "msg": MIMEText(message, 'plain', 'utf-8'),
        #     "receiver": request.data['form']['email']
        # })
        mail.update({
            "host": "smtp.qq.com",
            "port": "465",
            "user": "1509629466@qq.com",
            "pwd": "byeixggsdizmhiad",
            "sender": "1509629466@qq.com",
            "subject": "[EatFun]账号注册验证码",  # 主题
            "msg": MIMEText(message, 'plain', 'utf-8'),
            "receiver": request.data['form']['email']
        })
        send_status = sendmail.sendmail(mail)
        if not send_status:
            return Response({"code": "no", "msg": "发送邮件失败，请稍后重试"})
        admins = Admins.objects.all()
        # print(request.data["form"])
        form = request.data['form']
        admins.create(**form, password=code)
        return Response({"code": "ok", "msg": "发送邮件成功，请尽快查看"})


# @csrf_exempt
# def register(request):
#     if request.method == 'POST':
#         print(request.POST)
#     return HttpResponse("hh")


class LoginView(APIView):
    authentication_classes = []

    def post(self, request, *args, **kwargs):
        admins = Admins.objects.all()
        admin = request.data
        userinfo = admins.filter(username=admin['username'])
        # 如果注册过
        if userinfo.exists():
            print(userinfo)
            password = userinfo[0].password
            if admin['password'] == password:
                username = admin['username']
                print(username)
                atoken = create_token('admin',username, i_ex=3600)
                # rtoken = createToken(username, i_ex=1080)
                return Response(
                    {"code": 0, "flag": userinfo[0].flag, "msg": "登录成功", 'atoken': atoken})
            else:
                return Response({"code": -1, "msg": "用户名或密码错误"})
        # 如果没有注册
        else:
            return Response({"code": -1, "msg": "账户不存在，请先注册"})


# @csrf_exempt
# def pwdchange(request):
#     print(request)
#     return Response("hhhhdssdsds")


# # 生成验证码或初始密码
# def randomsting(randomlength=16):
#     random_str = ''
#     base_str = 'ABCDEFGHIGKLMNOPQRSTUVWXYZabcdefghigklmnopqrstuvwxyz0123456789'
#     length = len(base_str) - 1
#     for i in range(randomlength):
#         random_str += base_str[random.randint(0, length)]
#     return random_str


class PWDForgetView(APIView):
    def post(self, request, *args, **kwargs):
        code = str(randomsting(16))  # 验证码
        admins = Admins.objects.all()
        userinfo = admins.filter(username=request.data['username'])
        if userinfo.exists():
            username = userinfo[0].username
            email = userinfo[0].email
            message = "Hi," + username + ".\n你的密码修改验证码是" + code
            mail = dict()
            # mail.update({
            #     "host": "smtp.yeah.net",
            #     "port": "465",
            #     "user": "eatfun_backend@yeah.net",
            #     "pwd": "SNMZYLPFMPJGXMPO",
            #     "sender": "eatfun_backend@yeah.net",
            #     "subject": "[EatFun]账号注册验证码",  # 主题
            #     "msg": MIMEText(message, 'plain', 'utf-8'),
            #     "receiver": email
            # })
            mail.update({
                "host": "smtp.qq.com",
                "port": "465",
                "user": "1509629466@qq.com",
                "pwd": "byeixggsdizmhiad",
                "sender": "1509629466@qq.com",
                "subject": "[EatFun]账号注册验证码",  # 主题
                "msg": MIMEText(message, 'plain', 'utf-8'),
                "receiver": email
            })
            send_status = sendmail.sendmail(mail)
            if not send_status:
                return Response({"code": -1, "msg": "发送邮件失败，请稍后重试"})
            userinfo.update(code=code)
            return Response({"code": 0, "msg": "验证码已发送，请查看"})
        else:
            return Response({"code": -1, "msg": "用户不存在，请先注册"})


class PWDChangeView(APIView):
    def post(self, request, *args, **kwargs):
        username = request.data['username']
        oldpwd = request.data['oldpwd']
        print(oldpwd)
        newpwd = request.data['newpwd']
        admins = Admins.objects.all()
        userinfo = admins.get(username=username)
        print('dd')
        if userinfo.password == oldpwd:
            userinfo.flag = 1
            userinfo.password = newpwd
            userinfo.save()
            print('fff')
        else:
            return Response({"code": -1, "msg": "用户名或密码错误"})
        print(username)
        return Response({"code": 0, "msg": "修改密码成功"})


class OnlyCheckView(APIView):
    authentication_classes = []
    def post(self, request, *args, **kwargs):
        print(request.data)
        admins = Admins.objects.all()
        mode = request.data['mode']
        checkname = request.data['checkname']
        if mode == 'username':
            userinfo = admins.filter(username=checkname)
        elif mode == 'phone':
            userinfo = admins.filter(phone=checkname)
        else:
            userinfo = admins.filter(email=checkname)
        if userinfo.exists():
            return Response({"code": -1, "msg": "{0}已经存在，请重新输入".format(mode)})
        else:
            return Response({"code": 0})
